<template>
    <Card dis-hover :bordered="false">
        <Form>
            <Row :gutter="24" type="flex" class="ivu-mb-16">
                <Col>
                <Button v-hasC="{
                          name: 'automation-push-create-push',
                          flag: 'v1/automation/push/create-push',
                      }" type="primary" @click="handleOpenDrawer(-1)">新增</Button>
                </Col>
            </Row>
        </Form>
        <div class="i-table-no-border">
            <Table highlight-row ref="table" :columns="columns" :loading="loading" :data="data">
                <template slot="room" slot-scope="{ row }">
                    <tag v-for="item in row.room" :key="item.index">{{
                        item
                        }}</tag>
                </template>
                <template slot-scope="{ row }" slot="info">
                    <a v-hasC="{
                          name: 'automation-push-update-push',
                          flag: 'v1/automation/push/update-push',
                      }" href="javaScript:;" @click="handleOpenDrawer(row)">编辑</a>
                    <Divider v-hasCC="[
                          {
                              name: 'automation-push-update-push',
                              flag: 'v1/automation/push/update-push',
                          },
                          {
                              name: '-v1-automation-push-delete-push',
                              flag: 'v1/automation/push/delete-push',
                          },
                      ]" type="vertical" />
                    <a v-hasC="{
                          name: '-v1-automation-push-delete-push',
                          flag: 'v1/automation/push/delete-push',
                      }" @click="deletePush(row)">删除</a>
                </template>
            </Table>
            <div class="ivu-mt ivu-text-center">
                <Page show-total show-elevator show-sizer :total="total" :current.sync="params.page"
                    :page-size="params.pageSize" :page-size-opts="pageOpts" @on-change="formSize"
                    @on-page-size-change="formChangePage" />
            </div>
            <Modal v-model="modal" width="650" :title="edit ? `编辑` : `新增`" :mask-closable="false"
                @on-cancel="handleDrawerCancel(modalname)">
                <Form :ref="modalname" :model="formItem" :rules="createRules" :label-width="100">
                    <FormItem label="数据类型：" prop="date_type">
                        <RadioGroup v-model="formItem.date_type">
                            <Radio :label="0">项目</Radio>
                            <Radio :label="4">客服微信</Radio>
                        </RadioGroup>
                    </FormItem>
                    <FormItem label="客服微信：" v-show="formItem.date_type == 4"  prop="relation_id">
                        <Select v-model="formItem.relation_id" multiple>
                            <Option v-for="item in wxlist" :value="item.id" :key="item.id">{{ item.wechatnick }}({{ item.nickname }})</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="项目：" required v-if="formItem.date_type == 0">
                        <span>{{projectname}}</span>
                    </FormItem>
                    <FormItem label="钉钉token：" prop="dingtalk_id">
                        <Input type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" v-model="formItem.dingtalk_id"
                            placeholder="请输入钉钉token" />
                    </FormItem>
                </Form>
                <div slot="footer">
                    <Button @click="handleDrawerCancel(modalname)">取消</Button>
                    <Button type="primary" :loading="remarksloading" @click="handleSubmit(modalname)">确定</Button>
                </div>
            </Modal>
        </div>
    </Card>
</template>

<script>
    import {
        alreadyPush,
        addAlreadyPush,
        editAlreadyPush,
        automationPush,
        getDepartmentRole
    } from '@/api/TApi/index.js';
    import { customerwechatlist } from '@api/hqapi/indexone'
    export default {
        /*  import引入的组件注入到components对象中使用  */
        components: {},
        data () {
            const validateToken = (rule, value, callback) => {
                if (value.includes('https://')) {
                    callback();
                } else {
                    callback(new Error('请正确输入包含https的钉钉token'));
                }
            };
            const validateRelationid = (rule, value, callback) => {
                if (this.formItem.date_type == 4 && !value) {
                    callback(new Error('请选微信客服'));
                } else {
                    callback();
                }
            };
            return {
                total: 0, //  分页总数
                remarksloading: false,
                pageOpts: [10, 20, 30, 50], //  分页每页数量
                params: { page: 1, pageSize: 10, ding_type: 3 }, //  请求参数
                edit: true, //  编辑true,新增false
                loading: false, //  加载中
                modal: false, //  模态框开启属性
                modalname: 'formItem',
                grid: { xl: 4, lg: 8, md: 12, sm: 24, xs: 24 }, //  layout布局
                roomList: [],
                role: [],
                isEdit: {},
                columns: [
                    {
                        title: '名称',
                        key: 'type_name',
                        tooltip: true,
                        ellipsis: true,
                        minWidth: 118
                    },
                    {
                        title: '钉钉机器人token',
                        key: 'dingtalk_id',
                        tooltip: true,
                        minWidth: 300
                    },
                    {
                        title: '操作人',
                        key: 'operation_name',
                        width: 100
                    },
                    {
                        title: '更新时间',
                        key: 'updated_at',
                        minWidth: 150
                    },
                    { title: '操作', slot: 'info', width: 150 }
                ], // 列表表头
                data: [], // 列表数据
                department: [],
                projectname: '',
                formItem: {
                    id: 0,
                    relation_id: 0,
                    dingtalk_id: '',
                    date_type: 0,
                    ding_type: 3
                },
                // 模态框数据
                createRules: {
                    relation_id: [{ validator: validateRelationid, required: true }],
                    dingtalk_id: [{ validator: validateToken, trigger: 'blur', required: true }],
                    date_type: [{ required: true, message: '请选数据类型', type: 'number', trigger: 'change' }]
                }, // 模态框验证规则
                wxlist: []
            };
        },
        /* 函数方法集合 */
        methods: {
            /* @函数功能: 初始化 */
            initial () {
                customerwechatlist().then(res => {
                    this.wxlist = res.list
                })
                this.askData();
            },
            /* @函数功能: 请求数据 */
            askData () {
                alreadyPush(this.params).then((res) => {
                    this.data = res.list.list;
                    this.roomList = res.clinic;
                    this.department = res.department;
                    this.total = res.list.total;
                });
            },
            deletePush (row) {
                this.$Modal.confirm({
                    title: '删除提示',
                    content: '请确认是否删除好友申请设置？',
                    loading: true,
                    onOk: () => {
                        automationPush({
                            id: row.id
                        })
                            .then((res) => {
                                this.$Message.success('删除成功');
                                this.$Modal.remove();
                                this.askData();
                            })
                            .catch((err) => {
                                this.$Modal.remove();
                        });
                    }
                });
            },
            /* @函数功能: 分页 */
            formSize (e) {
                this.params.page = e;
                this.askData();
            },
            /* @函数功能: 每页数量 */
            formChangePage (e) {
                this.params.pageSize = e;
                this.askData();
            },
            /* @函数功能: 打开新增或编辑 */
            handleOpenDrawer (row) {
                this.$refs[this.modalname].resetFields();
                if (row === -1) {
                    this.formItem = {
                        id: 0,
                        relation_id: 0,
                        dingtalk_id: '',
                        date_type: 0,
                        ding_type: 3
                    }
                    this.edit = false;
                    this.modal = true;
                } else {
                    this.formItem = {
                        id: row.id,
                        relation_id: row.relation_id.split(','),
                        dingtalk_id: row.dingtalk_id,
                        date_type: +row.date_type,
                        ding_type: 3
                    }
                    setTimeout(() => {
                        this.formItem = {
                            id: row.id,
                            relation_id: row.relation_id.split(','),
                            dingtalk_id: row.dingtalk_id,
                            date_type: +row.date_type,
                            ding_type: 3
                        }
                        this.edit = true;
                        this.modal = true;
                    })
                }
            },
            /* @函数功能: 新增或编辑提交 */
            handleSubmit (name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.logs(11111)
                        this.remarksloading = true;
                        this.logs(this.formItem)
                        let list = []
                        if (this.formItem.date_type == 0) {
                            list = [{
                                relation_id: '',
                                dingtalk_id: this.formItem.dingtalk_id,
                                date_type: this.formItem.date_type,
                                ding_type: 3
                            }]
                        } else {
                            for (let item of this.formItem.relation_id) {
                                list.push({
                                    relation_id: item,
                                    dingtalk_id: this.formItem.dingtalk_id,
                                    date_type: this.formItem.date_type,
                                    ding_type: 3
                                })
                            }
                        }
                        let params = {
                            id: this.formItem.id,
                            list
                        }
                        if (this.edit) {
                            editAlreadyPush(params).then((res) => {
                                this.askData();
                                this.$Message.success('编辑成功');
                                this.formItem = {
                                    id: 0,
                                    relation_id: 0,
                                    dingtalk_id: '',
                                    date_type: 0,
                                    ding_type: 3
                                }
                                this.modal = false;
                            }).finally(() => {
                                this.remarksloading = false;
                            });
                        } else {
                            addAlreadyPush(params).then((res) => {
                                this.askData();
                                this.$Message.success('新增成功');
                                this.formItem = {
                                    id: 0,
                                    relation_id: 0,
                                    dingtalk_id: '',
                                    date_type: 0,
                                    ding_type: 3
                                }
                                this.modal = false;
                            }).finally(() => {
                                this.remarksloading = false;
                            });
                        }
                    }
                });
            },
            /* @函数功能: 取消新增或编辑 */
            handleDrawerCancel (name) {
                this.formItem = {
                    id: 0,
                    relation_id: 0,
                    dingtalk_id: '',
                    date_type: 0,
                    ding_type: 3
                }
                this.modal = false;
            }
        },
        /* 挂载完成能访问DOM元素 */
        mounted () {
            this.initial();
            let currentProject = JSON.parse(window.localStorage.getItem('currentProject'))
            let projectlist = JSON.parse(window.localStorage.getItem('project'))
            projectlist.forEach(element => {
                if (element.project_id == currentProject) {
                    this.projectname = element.name
                }
            });
        },
        /* 创建之前 */
        beforeCreate () { },
        /* 挂载之前 */
        beforeMount () { },
        /* 更新之前 */
        beforeUpdate () { },
        /* 更新之后 */
        updated () { },
        /* 销毁之前 */
        beforeDestroy () { },
        /* 销毁完成 */
        destroyed () { },
        /* 有keep-alive缓存即会触发 */
        activated () { }
    };
</script>

<style lang="less" scoped></style>
